import { useEffect, useState } from "react";
import { useAtomValue } from "jotai";
import { Button, DatePicker, Select, Table } from "antd";
import SearchIcon from "@/assets/icons/search.svg?jsx";
import useFetch from "@/lib/hooks/useFetch";
import { getDeviceList } from "@/lib/api/device";
import { tokenAtom } from "@/store/user";
import { useMessage } from "@/providers/AntdMessageProvider";
import useOnMounted from "@/lib/hooks/useOnMounted";
import useOnUpdated from "@/lib/hooks/useOnUpdated";
import { getDeviceAlarmLogs } from "@/lib/api/log";
import { formatTime } from "@/lib/utils/time";
import clsm from "@/lib/utils/clsm";

type WarningProps = {
  visible: boolean;
};
export default function Warning(props: WarningProps) {
  const { visible } = props;
  const [searchData, setSearchData] = useState({
    device: null as number | null,
    time: null as string[] | null,
  });
  const [pagination, setPagination] = useState({
    index: 1,
    size: 10,
    total: 0,
  });

  const token = useAtomValue(tokenAtom);
  const message = useMessage();

  const {
    isLoading: isDeviceListLoading,
    data: deviceList,
    refetch: loadDeviceList,
    cancel: cancelLoadDeviceList,
  } = useFetch({
    fetchFn: (
      payload: { pageNum: number; pageSize: number },
      signal: AbortSignal,
    ) =>
      getDeviceList(payload, token, signal).then((res) => {
        if (res.code !== 200) {
          throw res;
        }
        return res.rows;
      }),
  });

  const {
    isLoading: isWarningLogsLoading,
    data: warningLogs,
    refetch: loadWarningLogs,
    cancel: cancelLoadWarningLogs,
  } = useFetch({
    fetchFn: (
      data: Parameters<typeof getDeviceAlarmLogs>[0],
      signal: AbortSignal,
    ) =>
      getDeviceAlarmLogs(data, token, signal).then((res) => {
        if (res.code !== 200) {
          throw res;
        }
        setPagination((p) => ({ ...p, total: res.total }));
        return res.rows;
      }),
  });

  function handleSearch() {
    if (!searchData.device) {
      message.error("请选择设备！");
      return;
    }
    if (!searchData.time) {
      message.error("请选择时间！");
      return;
    }
    cancelLoadWarningLogs();
    loadWarningLogs({
      pageSize: pagination.size,
      pageNum: pagination.index,
      deviceId: searchData.device,
      startTime: searchData.time[0],
      endTime: searchData.time[1],
    });
  }

  useOnUpdated(() => {
    handleSearch();
    return () => {
      cancelLoadWarningLogs();
    };
  }, [pagination.index, pagination.size]);

  useEffect(() => {
    if (visible && !deviceList) {
      loadDeviceList({ pageNum: 1, pageSize: 999 });
    }
    return () => {
      cancelLoadDeviceList();
    };
  }, [visible, deviceList, loadDeviceList, cancelLoadDeviceList]);

  return (
    <div className={clsm(!visible && "hidden")}>
      <div className="flex justify-center gap-x-4">
        <Select
          loading={isDeviceListLoading}
          value={searchData.device}
          style={{ width: 200 }}
          onChange={(v) => setSearchData((p) => ({ ...p, device: v }))}
          allowClear
          showSearch
          optionFilterProp="label"
          placeholder="选择设备"
        >
          {deviceList?.map((device) => (
            <Select.Option
              key={device.deviceId}
              label={device.deviceName}
              value={device.deviceId}
            >
              {device.deviceName}
            </Select.Option>
          ))}
        </Select>
        <DatePicker.RangePicker
          showTime
          onChange={(v) =>
            setSearchData((p) => ({
              ...p,
              time:
                v && v[0] && v[1]
                  ? [
                      v[0].format("YYYY-MM-DD HH:mm:ss"),
                      v[1].format("YYYY-MM-DD HH:mm:ss"),
                    ]
                  : null,
            }))
          }
        />
        <Button loading={isWarningLogsLoading} onClick={handleSearch}>
          <SearchIcon />
        </Button>
      </div>
      <div className="mt-8 px-10">
        <Table
          loading={isWarningLogsLoading}
          dataSource={warningLogs || []}
          pagination={{
            total: pagination.total,
            current: pagination.index,
            pageSize: pagination.size,
            onChange(index, size) {
              setPagination((p) =>
                p.size === size
                  ? { ...p, index, size }
                  : { ...p, index: 1, size },
              );
            },
          }}
        >
          <Table.Column title="报警名称" dataIndex="alarmName" />
          <Table.Column
            title="报警时间"
            render={(row) => formatTime(row.alarmTime, "YYYY-MM-DD HH:mm:ss")}
          />
          <Table.Column title="设备" dataIndex="deviceName" />
          <Table.Column
            title="报警类型"
            render={(row) => (
              <span>{row.alarmType === "running" ? "运行" : "设备"}报警</span>
            )}
          />
        </Table>
      </div>
    </div>
  );
}
